<template>
  <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
    <template #operator>
      <div>
        <a-button type="primary" @click="handelActionTable">
          <PlusOutlined />
          新增制品工具
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'artifactName'">
        <span>{{ record.artifactName }}</span>
        <span v-if="record.projectCode === PordDefaultData.internalArtifact" class="artifactName-tag">默认全局</span>
      </template>
      <template v-if="column.dataIndex === 'password'">
        <div class="table-password">
          <span class="table-password-text">{{ record.showPassword ? record.password : '************' }}</span>
          <span class="table-password-icon" @click="record.showPassword = !record.showPassword">
            <SvgIcon
              v-if="record.showPassword"
              class="iconDef"
              :name="'eyes'"
              :color="'#1890ff'"
              width="16"
              height="16"
            />
            <SvgIcon v-else class="iconDef" :name="'eyesClose'" :color="'#1890ff'" width="16" height="16" />
          </span>
        </div>
      </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelDetial(record)">详情</a>
          <a v-if="record.projectCode !== PordDefaultData.internalArtifact" @click="handelEdit(record)">编辑</a>
          <a v-if="record.projectCode !== PordDefaultData.internalArtifact" @click="handelDelete(record)">删除</a>
        </div>
      </template>
    </template>
  </Table>

  <BasicModal
    ref="showActionModal"
    :title="`${ModalName[type]}制品`"
    width="500px"
    :confirmLoading="editArtifatToolsLoading"
    @emit-callback-fn="modalCallbackFn($event)"
  >
    <template #content> <SchemaForm ref="formRef" /></template>
  </BasicModal>
</template>

<script setup lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  queryArtifactRespositoryPageListFun,
  addArtifactRespositoryPageListFun,
  putArtifactRespositoryPageListFun,
  deleteArtifactRespositoryPageListFun,
} from '@/api/artifactRepository';
import { Modal, message } from 'ant-design-vue';
import { createVNode } from 'vue';
import { ModalName, ModalType, PordDefaultData } from '@/enums/commonEnum';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import {
  validatorCode,
  artifactTypeOptions,
  storagePolicyOptions,
  validatorUrl,
  validatorPassword,
} from '@/settings/commonSettings';
import * as CryptoUtils from '@/utils/cryptoUtils';
const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'artifactName', title: '工具名称', align: 'center', ellipsis: true },
  { dataIndex: 'artifactType', title: '仓库类型', align: 'center', ellipsis: true },
  { dataIndex: 'artifactCode', title: '仓库编码', align: 'center', ellipsis: true },
  { dataIndex: 'serverAddress', title: '服务地址', align: 'center', ellipsis: true },
  { dataIndex: 'userName', title: '用户名', align: 'center', ellipsis: true },
  { dataIndex: 'password', title: '密码', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];
const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'artifactName',
      label: '工具名称',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: (_, value: any) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                reject(new Error('工具名称不能为空'));
              } else if (value.length > 20) {
                reject(new Error('请输入20字符内的工具名称'));
              } else {
                resolve();
              }
            });
          },
        },
      ],
      component: 'Input',
    },
    {
      field: 'artifactType',
      label: '仓库类型',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: {
        options: artifactTypeOptions,
      },
      component: 'Select',
    },
    {
      field: 'artifactCode',
      label: '仓库编码',
      labelWidth: 90,
      required: true,
      rules: [
        {
          required: true,
          validator: (_, value: any) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                reject(new Error('仓库编码不能为空'));
              } else if (!validatorCode.test(value)) {
                reject(new Error('请输入长度不超过50字符的小写字母、数字或中划线，且不能以中划线开头或结尾。'));
              } else {
                resolve();
              }
            });
          },
        },
      ],
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'serverAddress',
      label: '服务地址',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: (_, value: any) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                reject(new Error('服务地址不能为空'));
              } else if (!validatorUrl.test(value)) {
                reject(new Error('URL格式不正确，请检查并重新输入。'));
              } else {
                resolve();
              }
            });
          },
        },
      ],
      component: 'Input',
    },
    {
      field: 'storageStrategy',
      label: '存储策略',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      vIf: ({ formModel }) => {
        return (formModel.artifactType as unknown as string) == 'MAVEN';
      },
      componentProps: {
        options: storagePolicyOptions,
      },
      component: 'CheckboxGroup',
    },
    {
      field: 'userName',
      label: '用户名',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'password',
      label: '密码',
      required: true,
      labelWidth: 90,
      colProps: {
        span: 22,
      },
      component: 'ActionPassWord',
    },
    {
      field: 'description',
      label: '描述',
      labelWidth: 90,
      required: false,
      colProps: {
        span: 24,
      },
      component: 'InputTextArea',
    },
  ] as FormSchema[],
});

const type = ref<ModalType>(ModalType.add);
const tableRef = ref<any>('');
const showActionModal = ref<any>(null);

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      dataSource: PordDefaultData.manufacturedTool,
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  return await queryArtifactRespositoryPageListFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records:
        res?.records
          .map((item: any) => {
            return {
              showPassword: false,
              ...item,
              password: CryptoUtils.decryptByRSA(item.password),
            };
          })
          .sort((a: any, b: any) => {
            if (
              a.projectCode === PordDefaultData.internalArtifact &&
              b.projectCode !== PordDefaultData.internalArtifact
            ) {
              return -1;
            }
            return 0;
          }) || [],
    };
    return data;
  });
};

const handelActionTable = async () => {
  type.value = ModalType.add;
  showActionModal.value.showModal();
};

//表格详情
const handelDetial = async (record: any) => {
  type.value = ModalType.detail;
  showActionModal.value.showModal(record, '关闭');
  let obj = { ...record, storageStrategy: record?.storageStrategy ? record.storageStrategy.split(',') : [] };
  nextTick(() => {
    formRef.setSchemaFormProps({ disabled: true });
    formRef.setFieldsValue(obj);
  });
};

const handelEdit = async (record: any) => {
  type.value = ModalType.edit;
  showActionModal.value.showModal(record);
  let obj = { ...record, storageStrategy: record?.storageStrategy ? record.storageStrategy.split(',') : [] };
  nextTick(() => {
    formRef.setFieldsValue(obj);
  });
};
const editArtifatToolsLoading = ref<boolean>(false);
const modalCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  editArtifatToolsLoading.value = true;
  let parameObj = {
    ...data,
    storageStrategy: data?.storageStrategy ? data?.storageStrategy.join(',') : '',
    projectCode: PordDefaultData.toolArtifact,
    projectName: PordDefaultData.toolArtifact,
    dataSource: PordDefaultData.manufacturedTool,
    openScope: PordDefaultData.openScope,
    password: CryptoUtils.encryptByRSA(data.password),
  } as OperationManagement.addArtifactPageListParams;

  if (type.value === ModalType.add) {
    await addArtifactRespositoryPageListFun(parameObj)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editArtifatToolsLoading.value = false;
      });
  }

  if (type.value === ModalType.edit) {
    await putArtifactRespositoryPageListFun({ ...obj.propsData, ...parameObj })
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editArtifatToolsLoading.value = false;
      });
  }
};

const handelDelete = async (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode(
      'div',
      { style: 'color:black;' },
      `确定要删除“制品工具：${record.artifactName}”这一项数据吗？`,
    ),
    async onOk() {
      await deleteArtifactRespositoryPageListFun(record.uuid).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};
</script>

<style scoped lang="less">
.table-password {
  display: flex;
  align-items: center;
  position: relative;
}

.table-password-text {
  margin-right: 5px;
  display: inline-block;
  width: 100%;
}

.table-password-icon {
  cursor: pointer;
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translate(0, -50%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.artifactName-tag {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 12px;
  color: #1890ff;
  background: #e6f7ff;
  border-color: #91d5ff;
  padding: 1px 5px;
  text-align: center;
}
</style>
